package bajo.src;

import java.util.Hashtable;
import java.util.Vector;

import javax.microedition.io.HttpConnection;

import net.rim.blackberry.api.browser.URLEncodedPostData;
import net.rim.device.api.ui.component.ButtonField;

/**
 * 
 * Class used to keep track of course information.
 * This class also represents the buttons in the tab 
 *
 */
public class Course extends ButtonField {
	private String code; // Code of this course.
	private String userID;
	private Vector posts; // Posts associated with this course.
	private Vector postListener; // Contain information determining if the button listener has been initiated.
	private String curTime; // Time of the last posted post. This is used to only download new posts.
	private Hashtable enrolledStudents;
	
	public Course(){
		code = "null";
		curTime = "";

		init();
	}

	public Course(String name, String userID){
		super(name);
		this.code = name;
		this.userID = userID;
		this.curTime = "";
		
		init();
	}
	
	/*
	 * Function where it will be invoked whenever this object has been
	 * initiated.
	 */
	private void init() {
		posts = new Vector();
		postListener = new Vector();		
		enrolledStudents = new Hashtable();
		// retrieve the enrolled students
		updateStudents();
		updatePostDB("", "", null);
		
	}
	
	public void updatePostUI(String[] retData){
		posts.removeAllElements();
		postListener.removeAllElements();
		// Print out the post to the screen.
		if(retData.length >=4){
			for (int i = 0; i < retData.length;){
				posts.addElement(new Post(retData[i++], retData[i++], retData[i++],retData[i++],
									"Remove Post", 65, 10));
				postListener.addElement(new Integer(0));
			}
			setTime(retData[retData.length-3]);
		}
	}
	
	public void updateStudents(){
		
		URLEncodedPostData postData = new URLEncodedPostData(URLEncodedPostData.DEFAULT_CHARSET, false);
		postData.append("courseCode", this.code);
		postData.append("userID", this.userID);
		String url = Constants.BASE_TOMCAT_ADDR + Constants.STUDENT_ENROLLED_SERVLET;
		CallBack callBack = new CallBack(){
			public void function(String[] data){
				enrolledStudents = new Hashtable();
				if( data.length>=3){
					for (int i = 0; i < data.length;){
						Student s = new Student(data[i++], data[i++], data[i++], "");
						s.setUsing(true);
						enrolledStudents.put(data[i], s);
					}
				}
			}
		};
		HTTPDataThread sendThread = new HTTPDataThread(url, postData, HttpConnection.POST, callBack, false);
		sendThread.start();	
		
	}
	
	/*
	 * Function where the user posts something it will add it to the list of 
	 * posts.
	 */
	public void updatePostDB(String poster, String msg, final MainPage mp) {
		// Get rid of the new line characters. This is required because servlet returns data is in String using the 
		// new line character as the delimiter.
		String newMsg = replaceNewLine(msg);
		String p = poster;
		// Startup a thread to query the database.
		if (newMsg == ""){
			p = "";
		}
		URLEncodedPostData postData = new URLEncodedPostData(URLEncodedPostData.DEFAULT_CHARSET, false);
		postData.append("userId", p);
		postData.append("courseCode", this.code);
		postData.append("msg", newMsg);
		postData.append("time", curTime);
		String url = Constants.BASE_TOMCAT_ADDR + Constants.ADD_POST_SERVLET;
		CallBack callBack = new CallBack(){
			public void function(String[] data){
				updatePostUI(data);
				if (mp != null){
					mp.updateAll(false);
					mp.addPostTxt.setFocus();
				}
			}
		};
		HTTPDataThread sendThread = new HTTPDataThread(url, postData, HttpConnection.POST, callBack, false);
		sendThread.start();
		
	}
	
	/*
	 * Function where it return the course code in String.
	 */
	public String getCode(){
		return code;		
	}
	
	public Hashtable getEnrolledStudents(){
		return enrolledStudents;
	}
	
	/*
	 * Setter for the last post time.
	 */
	public void setTime( String newTime){
		this.curTime = newTime;
	}
	
	/*
	 * Helper function to replace newline characters with 4 spaces.
	 */
	private String replaceNewLine(String str){
		String result="";
		char temp;
		for(int i=0; i<str.length();i++){
			temp = str.charAt(i);
			if (temp != '\n'){
				result+=str.charAt(i);
			}else{
				result+= " ";
			}
		}
		return result;
	}
	
	/*
	 * Returns the Vector with Post objects.
	 */
	public Vector getPosts() {
		return posts;
	}
	
	/*
	 * Returns the Vector with Integer objects.
	 */
	public Vector getPostListener() {
		return postListener;
	}
	
	/*
	 * Reset the Vector with Post objects and Integer objects.
	 */
	public void setPostVector(Vector post, Vector postL) {
		this.posts = post;
		this.postListener = postL;
	}
}
